import { Component, OnInit, OnDestroy, } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { MenuService } from '../../core/services/menu.service';
import { BoardService } from './board.service';
import { MapService } from '../../core';
import { MainFormatService } from '../../core/services/main-format.service';
import { PdfViewerComponent, VideoComponent } from 'src/app/shared/components';
import { ToolService } from '../../core/services/tool.service';
import { LayerManageService } from '../../core/services/layer-manage.service';
import { LayerMessageService } from '../../core/services/layer-message.service';
@Component({
  selector: 'app-board',
  templateUrl: './board.component.html',
  styleUrls: ['./board.component.scss']
})
export class BoardComponent implements OnInit, OnDestroy {
  title = '路段查看';
  menuList = null;
  // 默认左侧菜单栏为关闭状态！初始化打开，然后路由离开再关闭掉！
  isOpen = false;
  resultlist = null;
  Landlist = null;
  menuItem = null;
  closeSelectItem = null;
  pdfUrl = null;
  currentPDFitem = null;
  currentBtn = 'PDF';
  // 当前项的pdf的索引值
  itemNum = 0;
  // 视频总数
  pdfNum = 0;
  videonum = 0;
  mapboxglmap = null;
  pagenNo = 1;
  totalRecord = 0;
  keyword = '';
  listItemInfo = null;
  timter = null;
  counter = 4;
  preitem = '';
  subscriptations = [];
  searchLayer = [
  ];
  m = 1;
  videolist = null;
  constructor(
    private boardService: BoardService,
    private apboxMapService: MapService,
    private mainFormatService: MainFormatService,
    private menuService: MenuService,
    private toolService: ToolService,
    private layerManageService: LayerManageService,
    private layerMsgService: LayerMessageService,
    private activatedRoute: ActivatedRoute,
    private router: Router,
  ) {
    const urlArr = router.url.split("/")
    if (urlArr && urlArr.length > 0) {
      const path = urlArr[urlArr.length - 1];
      this.getSideMenuList(path);
    }
  }
  ngOnInit() {
    this.apboxMapService.init().then((mapboxglmap: any) => {
      this.mapboxglmap = mapboxglmap;
      if (mapboxglmap.isStyleLoaded()) {
        this.mapInit(mapboxglmap);
      } else {
        mapboxglmap.on('load', () => {
          this.mapInit(mapboxglmap);
        });
      }
    });
    this.getList('plotx.list');
    this.isOpen = true;

    // 关闭二级查询条件面板以及标识绘制的面板以及查询结果列表面版以及识别出来的详情信息框面板！
    this.subscriptations.push(
      postal.channel('TWOLEVEL_PANEL_CHANNEL').subscribe('twolevel-panel', res => {
        this.close(true);
      })
    );
  }
  mapInit(mapboxglmap) {
    this.mapboxglmap.on('click', (e) => {
      const bbox = [
        [e.point.x - 3, e.point.y - 3],
        [e.point.x + 3, e.point.y + 3]
      ];
      if (this.layerManageService.isOpenLayer(this.mapboxglmap, 'zjcsj_jcld_lYJC')) {
        const features = mapboxglmap.queryRenderedFeatures(bbox, {
          layers: ['zjcsj_jcld_lYJC']
        });
        if (features && features.length > 0) {
          const { gid } = features[0].properties;
          const params = { gid: gid };
          this.videolist = null;
          this.m = 1;
          this.getPDFVideo('pdf.video.road', params, '路段查看', 'hightlight_line', 'zjcsj_jcld_lWJC',);
        }
      }
      if (this.layerManageService.isOpenLayer(this.mapboxglmap, 'zjcsj_jcxq_pt')) {
        const features = mapboxglmap.queryRenderedFeatures(bbox, {
          layers: ['zjcsj_jcxq_pt']
        });
        if (features && features.length > 0) {
          const { gid } = features[0].properties;
          const params = { gid: gid };
          this.getPDFVideo('pdf.video.ov', params, '小区查看', 'hightlight_point', '');
        }
      }
    });
    if (this.menuList) {
      this.publishMessage({ data: this.menuList[0], visible: true });
    }
  }
  getPDFVideo(serviceID, params, titles, style, beforId) {
    this.boardService.getVideoPDF(serviceID, params).subscribe(res => {
      if (res.code === 1 && res.data) {
        // <---------------------------------------（1）先清空--------------------------------------------->
        this.resultlist = null;  // 二级详情结果列表
        this.listItemInfo = null; // pdf、video内容列表
        // <------------------------（2）格式化数据用于pdf、video组件去展示---------------------------------->
        const list = this.mainFormatService.fieldAdaptive(res.data, [['mc', 'title'], ['jczt', 'tag']]);
        this.resultlist = this.boardService.dataFormate(res.data);  // 还原二级详情结果列表
        this.totalRecord = 1;
        this.formatPdfVideoData(this.resultlist[0]);  // 还原pdf、video内容列表
        // <-----------------------（3）二级菜单展示出来，同时侧边栏要有选中项-------------------------------->
        const datas = { title: titles, visible: true };
        postal.channel('TWOLEVEL_PANEL_CHANNEL').publish('cctv-twopanel', datas);  // 打开二级详情菜单(只传递currentSelect，其他的还在这个组件中处理)
        this.menuItem = { data: datas, visible: true };
        // <--------------------------------------（4）地图操作--------------------------------------------->
        // 地图高亮
        this.layerManageService.removeLayer();
        const { geo } = this.resultlist[0];
        this.layerManageService.addUniLayer(geo, style, beforId);
      }
    });
  }
  close(e) {
    this.closeSelectItem = {
      visible: false
    };
    this.listItemInfo = null;
    this.layerManageService.removeLayer();
  }
  search() {
    const { serviceID } = this.menuItem.data;
    this.toolService.throttle(this.getList(serviceID), 2000);
  }
  getSideMenuItem(e) {
    this.menuItem = e;
    const { serviceID } = e.data;
    const title = e.data.title;
    this.publishMessage(e);
    if (!(e.visible)) {
      this.resultlist = null;
      this.totalRecord = 0;
      // 目的：关闭三级详情页
      this.listItemInfo = null;
      postal.channel('PIPE_CHANNEL').publish('sewage-isopen', false);
      return;
    } else {
      this.pagenNo = 1;
      this.getList(serviceID);
      if (title === '小区查看' && e.visible) {
        postal.channel('PIPE_CHANNEL').publish('sewage-isopen', true);
      }
    }
    this.layerManageService.removeLayer();
    this.listItemInfo = null;
  }
  publishMessage(e) {
    const { rlayer } = e.data;
    this.layerMsgService.clearSpecleLayer(this.menuList);
    if (e.visible) {
      const controllTree = { rlayer: rlayer, active: true };
      this.layerMsgService.publishControllLayer(controllTree);
    }
  }
  getSideMenuList(id) {
    this.menuService.getSideMenuList(id).subscribe(res => {
      this.menuList = res;
      this.menuItem = res[0];
    });
  }
  // 分页查询
  pageIndexChange() {
    const { serviceID } = this.menuItem.data;
    this.getList(serviceID);
  }
  getVideoList(e) {
    const response = this.listItemInfo.spcflj;
    this.videolist = response.slice(e * 4, 4 * e + 4);
  }
  getList(serviceID) {
    const param = {
      keyword: this.keyword,
      pageSize: 10,
      pageNo: this.pagenNo
    };
    this.boardService.backServiceData(serviceID, param, [['mc', 'title'], ['jczt', 'tag']], (list, total) => {
      if (list) {
        this.resultlist = list;
        this.totalRecord = total;
      } else {
        this.resultlist = null;
        this.totalRecord = 0;
      }
    });
  }
  zoomto(e) {
    this.formatPdfVideoData(e);
    this.layerManageService.fitPositionAddLayer(this.mapboxglmap, e, 'hightlight', 'zjcsj_jcld_lWJC', true);
  }

  formatPdfVideoData(data) {
    this.listItemInfo = data;
    if (data.bgcflj || data.spcflj) {
      // 获取PDF数量
      this.pdfNum = this.listItemInfo.bgcflj ? this.listItemInfo.bgcflj.length : 0;
      // 获取视频数量
      this.videonum = this.listItemInfo.spcflj ? this.listItemInfo.spcflj.length : 0;
      // 立刻获取到首个PDF信息
      if (this.listItemInfo.bgcflj && this.listItemInfo.bgcflj.length > 0) {
        this.pdfUrl = this.listItemInfo.bgcflj[0].path;
        // this.currentPDFitem = this.listItemInfo.bgcflj[0];
      } else {
        this.pdfUrl = null;
      }
      if (this.listItemInfo && this.listItemInfo.spcflj.length > 0) {
        this.getMoreData();
      }
    }
  }
  getMoreData() {
    //m:button点击次数 n:一次加载几条数据
    const response = this.listItemInfo.spcflj;
    this.videolist = response.slice(4 * (this.m - 1), 4 * (this.m - 1) + 4);
  }
  changeInfo(e) {
    if (e === 'Video') {
      this.m = 1;
      this.videolist = null;
      this.getMoreData();
    }
  }
  closePDF(e) {
    this.listItemInfo = null;
  }
  readPDF(e, index) {
    this.currentPDFitem = e;
    this.pdfUrl = e.path;
    this.itemNum = index;
  }
  readVideo(e) {
    this.boardService.openModel('CCTV检测视频', VideoComponent, e.path);
  }
  preview(item) {
    this.boardService.openModel('CCTV检测报告', PdfViewerComponent, item.path);
  }
  ngOnDestroy() {
    this.layerManageService.removeLayer();
    this.isOpen = false;
    clearInterval(this.timter);
    // 取消订阅
    this.subscriptations.forEach(element => {
      element.unsubscribe();
    });
    this.layerMsgService.clearSpecleLayer(this.menuList);
  }
}
